package cn.wx;

import cn.wx.api.WxMpServiceProxy;
import cn.wx.common.WxServiceRegister;
import cn.wx.common.WxServiceRegisterPostProcessor;
import cn.wx.common.properties.WxProperties;
import cn.wx.properties.WxMpProperties;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.core.annotation.Order;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.lang.reflect.Proxy;
import java.util.List;

import static cn.wx.properties.WxMpProperties.PREFIX;

/**
 * 微信公众平台注册,使用配置文件的方式
 *
 * @author: sunshaoping
 * @date: Create by in 5:11 下午 2020/5/25
 */
@Order(9)
@AllArgsConstructor
public class WxMpServiceRegisterPostProcessor implements WxServiceRegisterPostProcessor {

    private final WxMpProperties properties;

    private final WxMpService wxMpService;

    @PostConstruct
    public void init() {

    }


    @Override
    public void processor(WxServiceRegister register) {
        //默认服务
        properties.verification(PREFIX);
        List<WxProperties> multiple = properties.getMultiple();
        if (CollectionUtils.isEmpty(multiple)) {
            return;
        }
        multiple.forEach(wxMpProperties -> {
            String name = wxMpProperties.getName();
            Object proxyInstance = Proxy.newProxyInstance(
                    WxMpService.class.getClassLoader(),
                    new Class[]{WxMpService.class},
                    new WxMpServiceProxy(name, wxMpService)
            );
            //注册bean处理
            register.register(name, proxyInstance);
        });
    }

}
